package com.witmore.skyline.web.service.third.tplink;

import com.alibaba.fastjson.JSONObject;
import com.witmore.skyline.web.controller.enums.WitmoreErrorCode;
import com.witmore.skyline.web.controller.vo.param.CameraParamVO;
import com.witmore.skyline.web.exception.WitmoreException;
import com.witmore.skyline.web.service.third.constants.ApiTpLinkClientConstant;
import com.witmore.skyline.web.service.third.tplink.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * Description: ApiVmsStreamClient
 * Author: 豆子高
 * Date: 2025/4/17 16:42
 */
@Slf4j
public class ApiVmsStreamClient {


    /**
     * 1.4.5.3获取音视频流访问地址
     * {
     * "error_code": 0,
     * "result": {
     * "sdkStreamUrl": "https://api-smbcloud.tp-link.com.cn/vms/open/webServer/v1/requestRelayUrl?token=13569-e3NhbHQgPSAyMDU1NTA1MzgyO2NsaWVu-95832f4d6ad74b8d80dde6199955f5e6&devInfoId=576620008413343087&clientUUID=0466ef9b1a31432e9faa74947f8feb70&clientType=chrome111.0&streamType=video&resolution=2"
     * }
     * }
     */
    public static String requestStreamUrl(CameraParamVO cameraParamVO) {
        try {
            // 请求体内容
            String payload = "{\"qrCode\": \"" + cameraParamVO.getCameraSn() + "\", " +
                    "\"channelId\": 1," +
                    "\"clientType\":\"" + cameraParamVO.getClientType() + "\"," +
                    "\"streamType\":\"" + cameraParamVO.getStreamType() + "\"," +
                    "\"resolution\":" + cameraParamVO.getResolution() + "}";
            TreeMap<String, String> headerTreeMap = ApiTPClient.authorizationReady(ApiTpLinkClientConstant.GET_STREAM_URL_PATH, payload);
            String response = ApiTPClient.sendPost(ApiTpLinkClientConstant.GET_STREAM_URL_URL, payload, headerTreeMap);
            if (StringUtils.isNotEmpty(response)) {
                TpResultDTO tpResultDTO = JSONObject.parseObject(response, TpResultDTO.class);
                String result = tpResultDTO.getResult();
                if (StringUtils.isNotEmpty(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    return jsonObject.getString("sdkStreamUrl");
                }
                return tpResultDTO.getResult();
            }
        } catch (Exception e) {
            log.error("提交抓图任务失败: 失败原因：{}", e.getMessage());
        }
        return null;
    }

    private static String tpClientHttpHandle(String path, String payload, String url, String methodName) {
        try {
            TreeMap<String, String> headerTreeMap = ApiTPClient.authorizationReady(path, payload);
            String response = ApiTPClient.sendPost(url, payload, headerTreeMap);
            if (StringUtils.isEmpty(response)) {
                throw new Exception("请求TP-Link接口【" + methodName + "】失败 ! response is null");
            }
            TpResultDTO tpResultDTO = JSONObject.parseObject(response, TpResultDTO.class);
            // 设备离线单独处理  {"error_code":-80327,"msg":"device offline"}
            if (null != tpResultDTO && null != tpResultDTO.getError_code() && tpResultDTO.getError_code() == -80327) {
                throw new WitmoreException(WitmoreErrorCode.CAMERA_OFF_LINE);
            }
            if (tpResultDTO == null || tpResultDTO.getError_code() == null || tpResultDTO.getError_code() != 0) {
                throw new Exception("请求TP-Link接口【" + methodName + "】失败 " + (tpResultDTO == null ? "tpResultDTO is null" : tpResultDTO.getResult()));
            }
            return tpResultDTO.getResult();
        } catch (Exception e) {
            throw new RuntimeException("请求TP-Link接口【" + methodName + "】失败: 失败原因：" + e.getMessage());
        }

    }

    /**
     * 1.4.5.7搜索存在回放录像的日期
     */
    public static List<DeviceVideoInfoDTO> getDeviceVideoInfoSearYear(List<String> cameraSns, String year) throws Exception {
        TpVideoBackYearParamDTO paramDTO = new TpVideoBackYearParamDTO();
        paramDTO.setYear(year);
        cameraSns.forEach(cameraSn -> {
            TpVideoBackYearParamDTO.QrCodeYearDTO qrCodeYearDTO = new TpVideoBackYearParamDTO.QrCodeYearDTO();
            qrCodeYearDTO.setChannelId(1);
            qrCodeYearDTO.setQrCode(cameraSn);
            paramDTO.getDevList().add(qrCodeYearDTO);
        });
        try {
            // 请求体内容
            String payload = JSONObject.toJSONString(paramDTO);
            String result = tpClientHttpHandle(ApiTpLinkClientConstant.GET_DEVICE_VIDEO_INFO_SEARCH_YEAR_PATH, payload,
                    ApiTpLinkClientConstant.GET_DEVICE_VIDEO_INFO_SEARCH_YEAR_URL, "搜索存在回放录像的日期");
            if (StringUtils.isEmpty(result)) {
                return new ArrayList<>();
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            String deviceVideoInfoList = jsonObject.getString("deviceVideoInfoList");
            if (StringUtils.isEmpty(deviceVideoInfoList)) {
                return new ArrayList<>();
            }
            return JSONObject.parseArray(deviceVideoInfoList, DeviceVideoInfoDTO.class);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 1.4.5.8搜索当天录像数据
     */
    public static DeviceVideoDayInfo getDeviceVideoInfoSearchDay(String cameraSn, String searchDay, Integer startIdx, Integer endIdx) throws Exception {
        try {
            // 请求体内容
            String payload = "{\"qrCode\": \"" + cameraSn + "\", " +
                    "\"channelId\": 1," +
                    "\"searchDay\":\"" + searchDay + "\"," +
                    "\"startIdx\":" + startIdx + "," +
                    "\"endIdx\":" + endIdx + "}";
            String result = tpClientHttpHandle(ApiTpLinkClientConstant.SEARCH_VIDEO_DAY_PATH, payload,
                    ApiTpLinkClientConstant.SEARCH_VIDEO_DAY_URL, "搜索当天录像数据");
            if (StringUtils.isEmpty(result)) {
                return new DeviceVideoDayInfo();
            }
            return JSONObject.parseObject(result, DeviceVideoDayInfo.class);
        } catch (Exception e) {
            throw new Exception("搜索当天录像数据失败：" + e.getMessage());
        }
    }

    /**
     * 1.4.5.9搜索当天所有人形侦测录像数据
     */
    public static DeviceVideoDayInfo searchHumanDetectionVideo(String cameraSn, String searchDay) throws Exception {
        try {
            // 请求体内容
            String payload = "{\"qrCode\": \"" + cameraSn + "\", " +
                    "\"channelId\": 1," +
                    "\"searchDay\":\"" + searchDay + "\"}";
            String result = tpClientHttpHandle(ApiTpLinkClientConstant.SEARCH_HUMAN_DETECTION_VIDEO_PATH, payload,
                    ApiTpLinkClientConstant.SEARCH_HUMAN_DETECTION_VIDEO_URL, "搜索当天所有人形侦测录像数据");
            if (StringUtils.isEmpty(result)) {
                return new DeviceVideoDayInfo();
            }
            return JSONObject.parseObject(result, DeviceVideoDayInfo.class);
        } catch (Exception e) {
            throw new Exception("搜索当天所有人形侦测录像数据失败：" + e.getMessage());
        }
    }

    /**
     * 1.4.4.6.1获取IPC/NVR设备SD卡信息
     */
    public static List<DeviceSDCardInfo> getDeviceSDCardInfo(String cameraSn) {
        try {
            // 请求体内容
            String payload = "{\"qrCode\": \"" + cameraSn + "\", " +
                    "\"channelId\": 1}";
            String result = tpClientHttpHandle(ApiTpLinkClientConstant.GET_DEVICE_SD_CARD_INFO_PATH, payload,
                    ApiTpLinkClientConstant.GET_DEVICE_SD_CARD_INFO_URL, "获取IPC/NVR设备SD卡信息");
            if (StringUtils.isEmpty(result)) {
                return new ArrayList<>();
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            String cardInfoListStr = jsonObject.getString("cardInfoList");
            return JSONObject.parseArray(cardInfoListStr, DeviceSDCardInfo.class);
        } catch (Exception e) {
            throw new WitmoreException(WitmoreErrorCode.SYSTEM_ERROR, "获取IPC/NVR设备SD卡信息失败：" + e.getMessage());
        }
    }

}
